<template>
  <div>

    <!--      筛选用户-->
    <el-input v-model="query" class="input-with-select" placeholder="请输入内容">
      <el-button slot="append" icon="el-icon-search" @click="users"></el-button>
    </el-input>
    <!--      /筛选用户-->

    <!--      添加用户-->
    <el-button class="set-user" type="primary" @click="setUserVisible = true">添加用户</el-button>
    <el-dialog :visible.sync="setUserVisible" title="添加用户">
      <el-form ref="setUserForm" :model="form" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="用户名:" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="密码:" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="邮箱:" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="手机:" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--      /添加用户-->

    <!--      用户列表-->
    <el-table
      :data="tableData"
      border
      class="table-m"
      stripe>
      <el-table-column
        label="#"
        type="index"
        width="48">
      </el-table-column>
      <el-table-column
        label="姓名"
        prop="username">
      </el-table-column>
      <el-table-column
        label="邮箱"
        prop="email">
      </el-table-column>
      <el-table-column
        label="电话"
        prop="mobile">
      </el-table-column>
      <el-table-column
        label="角色"
        prop="role_name">
      </el-table-column>
      <el-table-column
        label="状态"
        prop="mg_state">
        <template slot-scope="scope">
          <el-switch v-model="tableData[scope.$index].mg_state"
                     @change="putUserState(tableData[scope.$index])"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        prop="操作">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit"
                     size="mini"
                     type="primary"
                     @click="setUserInfo(scope.$index, scope.row)"
          ></el-button>
          <el-button icon="el-icon-delete"
                     size="mini"
                     type="danger"
                     @click="removeUser(scope.$index, scope.row)"
          ></el-button>
          <el-button icon="el-icon-setting"
                     size="mini"
                     type="warning"
                     @click="setRole(scope.$index, scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--      修改用户信息-->
    <el-dialog :visible.sync="putUserInfoVisible" title="修改用户">
      <el-form ref="putInfoForm" :model="userInfoFrom" :rules="userInfoRules">
        <el-form-item :label-width="formLabelWidth" label="用户名:">
          <el-input v-model="userInfoFrom.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="邮箱:" prop="email">
          <el-input v-model="userInfoFrom.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="手机号:" prop="mobile">
          <el-input v-model="userInfoFrom.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="putUserInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="putUserInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!--      设置用户角色-->
    <el-dialog :visible.sync="setRoleVisible" class="roleFrom" title="分配角色">
      <el-form :model="roleFrom">
        <el-form-item label-width="200px">
          <template #label>
            <span>当前的用户: {{ roleUsername }}</span>
            <br>
            <span>当前的角色: {{ thisRoleName }}</span>
          </template>
        </el-form-item>
        <el-form-item label="分配新角色:" label-width="100px">
          <el-select v-model="roleFrom.role" placeholder="请选择">
            <el-option v-for="item in roleNameList"
                       :key="item.id"
                       :label="item.roleName"
                       :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="getRolesInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!--      /用户列表-->

    <!--      底部分页-->
    <div class="block">
      <el-pagination
        :current-page="pagenum"
        :page-size="100"
        :page-sizes="[2, 4, 8, 10]"
        :total="pieces"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    <!--      /底部分页-->
  </div>
</template>

<script>
import {
  getUsers,
  setUser,
  putUserState,
  deleteUser,
  getUserInfo,
  putUserInfo,
  getRolesInfo,
  putRolesInfo
} from '@/api/users'

export default {
  name: 'users',
  data () {
    return {
      // 获取用户信息的条件
      query: '',
      pagenum: 1,
      pagesize: 2,
      // 用户数据
      tableData: [],
      // 分页设置
      pieces: 1,
      // 弹框
      setUserVisible: false,
      putUserInfoVisible: false,
      setRoleVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userInfoFrom: {
        id: '',
        email: '',
        mobile: '',
        username: ''
      },
      // 表单内宽
      formLabelWidth: '80px',
      // 表单验证规则
      reg: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      rules: {
        username: [
          {
            required: true,
            min: 1,
            message: '请输入用户名称',
            trigger: 'blur'
          }, {
            min: 2,
            max: 7,
            message: '长度在 2 到 7 个字符',
            trigger: 'blur'
          }

        ],
        password: [
          {
            required: true,
            min: 1,
            message: '请输入密码',
            trigger: 'blur'
          }, {
            min: 2,
            max: 7,
            message: '长度在 2 到 7 个字符',
            trigger: 'blur'
          }

        ],
        email: [
          {
            required: true,
            min: 1,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }

        ],
        mobile: [
          {
            required: true,
            min: 1,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: this.validatemobile,
            trigger: 'blur'
          }

        ]
      },
      userInfoRules: {
        email: [
          {
            required: true,
            min: 1,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }

        ],
        mobile: [
          {
            required: true,
            min: 1,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: this.validatemobile,
            trigger:
              'blur'
          }

        ]
      },
      roleFrom: {
        id: '',
        role: ''
      },
      roleNameList: [],
      roleUsername: '',
      thisRoleName: ''
    }
  },
  created () {
    this.users()
  },
  methods: {
    // 获取用户信息列表
    async users () {
      try {
        const res = await getUsers({
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        })
        // console.log(res)
        if (res.meta.status === 200) {
          // 解决有时候会没有数据返回的bug
          if (res.data.users.length === 0) {
            this.pagenum = Math.ceil(res.data.total / this.pagesize)
            return this.users
          }
          this.tableData = res.data.users
          this.pieces = res.data.total
          this.pagenum = res.data.pagenum
        } else {
          this.$message.error(res.meta.msg)
        }
      } catch {
        this.$message.error('获取用户列表失败')
      }
    },
    // 添加用户信息
    async setUser () {
      try {
        await this.$refs.setUserForm.validate(async (valid) => {
          if (valid) {
            const res = await setUser(this.form)
            if (res.meta.status === 201) {
              this.$message({
                message: res.meta.msg,
                type: 'success'
              })
            } else {
              this.$message.error(res.meta.msg)
            }
            this.setUserVisible = false
          }
        })
      } catch {
        this.$message.error('添加用户失败')
      }
    },
    // 自定义手机号验证
    validatemobile (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    },
    // 修改用户状态
    async putUserState (thisUser) {
      try {
        const res = await putUserState(thisUser.id, thisUser.mg_state)
        if (res.meta.status === 200) {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
        } else {
          this.$message.error(res.meta.msg)
          thisUser.mg_state = !thisUser.mg_state
        }
      } catch {
        this.$message.error('修改状态失败')
        thisUser.mg_state = !thisUser.mg_state
      }
    },
    // 编辑用户信息
    async setUserInfo (index, str) {
      try {
        const res = await getUserInfo(str.id)
        // console.log(res)
        if (res.meta.status === 200) {
          // this.$message({
          //   message: res.meta.msg,
          //   type: 'success'
          // })
          this.userInfoFrom = {
            id: res.data.id,
            email: res.data.email,
            mobile: res.data.mobile,
            username: res.data.username
          }
          this.putUserInfoVisible = true
        } else {
          this.$message.error(res.meta.msg)
        }
      } catch {
        this.$message.error('用户信息获取失败')
      }
    },
    async putUserInfo () {
      await this.$refs.putInfoForm.validate(async (valid) => {
        if (valid) {
          const {
            id,
            email,
            mobile
          } = this.userInfoFrom
          try {
            const res = await putUserInfo(id, email, mobile)
            if (res.meta.status === 200) {
              this.$message({
                message: res.meta.msg,
                type: 'success'
              })
              this.putUserInfoVisible = false
              await this.users()
            } else {
              this.$message.error(res.meta.msg)
            }
          } catch {
            this.$message.error('修改用户信息失败')
          }
        }
      })
    },
    // 删除用户信息
    removeUser (index, str) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log(str.id)
        deleteUser(str.id).then(res => {
          if (res.meta.status === 200) {
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
          } else {
            this.$message.error(res.meta.msg)
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改用户角色
    async setRole (index, str) {
      try {
        const res = await getRolesInfo()
        this.roleNameList = res.data
        // console.log(res)
        this.setRoleVisible = true
        // console.log(str)
        this.roleUsername = str.username
        this.thisRoleName = str.role_name
        this.roleFrom.id = str.id
      } catch {

      }
    },
    async getRolesInfo () {
      if (this.roleFrom.role !== '') {
        const {
          id,
          role
        } = this.roleFrom
        try {
          const res = await putRolesInfo(id, role)
          if (res.meta.status === 200) {
            this.roleFrom.role = ''
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
            this.setRoleVisible = false
            await this.users()
          } else {
            this.$message.error(res.meta.msg)
          }
        } catch {
          this.$message.error('修改用户角色失败')
        }
      } else {
        this.$message.error('亲,请选择角色呦')
      }
    },
    // 分页操作
    handleSizeChange (value) {
      this.pagesize = value
      this.users()
    },
    handleCurrentChange (value) {
      this.pagenum = value
      this.users()
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .table-m * {
  font-size: 12px;
}

/deep/ .set-user {
  margin-left: 20px !important;
}

.table-m {
  margin: 15px 0;
}

/deep/ .input-with-select {
  width: 405px;
}

/deep/ .roleFrom {
  .el-form-item {
    margin-bottom: 14px;

    .el-form-item__label {
      text-align: left;
    }

  }

  .el-form-item:first-child {
    .el-form-item__label {
      line-height: 30px;
    }
  }
}

</style>
